/**
 * Writed by yura and mak
 */

package wz.legend.handlers.steps;

import org.apache.log4j.Logger;

import wz.legend.Context;
import wz.legend.HttpContext;
import wz.legend.handlers.info.InfoConstants;
import wz.legend.util.ParseUtils;
import wz.legend.util.UriConstants;
import wz.legend.util.Utils;


public class WalkingStep extends AbstractStep {

    private static final Logger LOG = Logger.getLogger(WalkingStep.class);

    private String crossName;
    private long stopedTime = 0;
    private boolean waitAreaTime = true;
    private String startArea = null;

    public WalkingStep() {
    }

    public void execute(Context context) {

        int index = Utils.getCrossIndex(context, crossName);
        LOG.debug("WalkingStep START cross " + crossName + " switchIndex="
                + index);
        context.getScriptStater().doScript("steps.walk.to",
                new String[] { Integer.toString(index) });
        state = State.START;
    }

    public void handle(HttpContext httpContext, Context context) {
        try {
            if (httpContext != null) {
                String uri = httpContext.getRequest().getRequestLine().getUri();
                if ((uri.contains(UriConstants.MAIN_FRAME) || uri
                        .endsWith(UriConstants.AREA_PHP))
                        && state == State.START) {
                    long areaTime = 0;
                    if (waitAreaTime) {
                        areaTime = (Integer) context
                                .getProperty(InfoConstants.AREA_TIME);
                    } else {
                        areaTime = 1;
                    }
                    stopedTime = areaTime * 1000 + System.currentTimeMillis();
                    state = State.ACTIVE;
                    LOG.debug("WalkingStep ACTIVE");
                }
            }
            if (state == State.ACTIVE
                    && stopedTime < System.currentTimeMillis()) {
                state = State.STOPED;
                LOG.debug("WalkingStep STOPED");
            }
        } catch (Exception e) {
            LOG.error(e, e);
            throw new RuntimeException(e);
        }
    }

    public boolean isWaitAreaTime() {
        return waitAreaTime;
    }

    public void setWaitAreaTime(boolean waitAreaTime) {
        this.waitAreaTime = waitAreaTime;
    }

    public String getCrossName() {
        return crossName;
    }

    public void setCrossName(String crossName) {
        this.crossName = crossName;
    }
}
